#! /usr/bin/python
# -*- coding: utf-8 -*-

# Copyright (c) 2011 - 2013 Stefano Mazzucco <stefano -at- curso.re>
# All rights reserved.
#
# This file is part of Crystalball Plus.
#
# Crystalball Plus is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Crystalball Plus is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Crystalball Plus.  If not, see <http://www.gnu.org/licenses/>.

if __name__ == '__main__':
    import sys
    import os.path
    from crystalballplus import *
    from crystalballplus.GUI.main import start_GUI

    usage = '\nUsage:\n\n'
    usage += "%s [[-GUI][-i input_path][-r reference_path][-d_err d_error][-a_err angle_error][-check all|any][-o][-d d_report][-a angle_report][-h]]\n\n" \
        % os.path.basename(sys.argv[0])
    usage += "Load the input and reference files (extension: .dfg),\n"
    usage += "and save the results in two report files (text format).\n"
    usage += "The user will be prompted to insert the parameters that have not"
    usage += " been specified.\n\n"
    usage += "OPTIONS\n"
    usage += "-GUI                    : start the GUI\n"
    usage += "-i <input_path>         : path to input file(s).\n"
    usage += "-r <reference_path>     : path to reference file(s).\n"
    usage += "-d_err <d_error>        : d-spacing error in %.\n"
    usage += "-a_err <a_error>        : angle error in %.\n"
    usage += "-check <all | any>      : angle check option.\n"
    usage += "-d <d_report>           : d-spacing report file.\n"
    usage += "-a <angle_report>       : angles report file.\n"
    usage += "-o                      : overwrite repots.\n"
    usage += "-v                      : print version and exit.\n"
    usage += "-h                      : print this message and exit.\n"
    usage += '\n'

    def checkoption(opt, msg, has_param=True, default=False):
        """Prompt message 'msg' and return the value of option 'opt'.

        Parameters
        ----------
        opt : string

        msg : string

        has_param : bool (optional)
                    if True (default), the value of 'opt' is returned
                    if e.g. one types in the shell ~$ program -i 10
                    the value "10" is returned
                    if False, 'opt' itself is returned

        default : bool (optional)
                  if True, a None is returned if the option is not found
                  if False (default) 'msg' is prompted and a value should
                  be given from raw_input

        Returns
        -------
        value : string

        """
        if opt in sys.argv:
            if has_param:
                return sys.argv[sys.argv.index(opt) + 1]
            else:
                return sys.argv[sys.argv.index(opt)]
        else:
            if has_param and default:
                try:
                    out = raw_input(msg)
                    if not out:
                        raise KeyboardInterrupt
                    return out
                except KeyboardInterrupt:
                    print(usage)
                    sys.exit(1)     # failure
            else:
                return None

    def printmsg(message, width=80, symbol='#'):
        message = '    ' + message + '    '
        print
        print(message.center(width, symbol))
        print

    if len(sys.argv) < 2:
        print(usage)
        sys.exit(0)

    h = checkoption('-h', '', False)
    if h == '-h':
        print(usage)
        sys.exit(0)

    v = checkoption('-v', '', False)
    if v == '-v':
        sys.exit(0)

    o = checkoption('-o', '', False)
    if o == '-o':
        o = True
    else:
        o = False

    gui = checkoption('-GUI', '', False)
    if gui == '-GUI':
        try:
            start_GUI()
            sys.exit(0)
        except NameError:
            print(sys.exc_info())
            print('\n\n####   GUI is not available   ####\n')
            print(usage)
            sys.exit(1)

    inp = checkoption('-i', 'Enter path to input file(s).\n')

    ref = checkoption('-r', 'Enter path to reference file(s).\n')

    par_D = {}
    try:
        d_err = float(checkoption('-d_err', '', True, False))
        d_err = d_err / 100
        par_D['minerr'] = d_err
    except TypeError:
        pass

    par_A = {}
    try:
        a_err = float(checkoption('-a_err', '', True, False))
        a_err = a_err / 100
        par_A['minerr'] = a_err
    except TypeError:
        pass

    check = checkoption('-check', '', True, False)
    if check is not None:
        par_A['check'] = check

    d_report = checkoption('-d', 'Enter path to d-spacing report file.\n')

    angle_report = checkoption('-a', 'Enter path to angle report file.\n')

    printmsg('COMPARING D-SPACINGS')
    try:
        D = compare_d(inp, ref, **par_D)
    except:
        printmsg('ERROR: ' + str(sys.exc_info()[1]))
        sys.exit(1)
    finally:
        printmsg('DONE')
    if D:
        printmsg('GENERATING D-SPACINGS REPORT')
        try:
            gen_d_report(D, d_report, ovrwrt=o)
        except:
            printmsg('ERROR: ' + str(sys.exc_info()[1]))
            sys.exit(1)
        finally:
            printmsg('DONE')
    else:
        printmsg('NO D-SPACINGS MATCH')
        printmsg('EXITING')
        sys.exit(1)
    try:
        printmsg('GROUPING REFLECTIONS')
        R = group_reflections(D)
        del D                   # try to save some memory
    except:
        printmsg('ERROR: ' + str(sys.exc_info()[1]))
        sys.exit(1)
    finally:
        printmsg('DONE')
    if R:
        printmsg('COMPARING ANGLES')
        try:
            A = compare_angles(R, **par_A)
            del R               # try to save some memory
        except:
            printmsg('ERROR: ' + str(sys.exc_info()[1]))
            sys.exit(1)
        finally:
            printmsg('DONE')
    else:
        printmsg('NO GROUPING REFLECTIONS')
        printmsg('EXITING')
        sys.exit(1)
    if A:
        printmsg('GENERATING ANGLE REPORT')
        try:
            gen_angle_report(A, angle_report, ovrwrt=o)
            del A               # try to save some memory
        except:
            printmsg('ERROR: ' + str(sys.exc_info()[1]))
            sys.exit(1)
        finally:
            printmsg('DONE')
    else:
        printmsg('NO ANGLE MATCH')
        printmsg('EXITING')
        sys.exit(1)

    sys.exit(0)                 # success
else:
    print('This file is meant to be executed from shell. Exiting.')
    sys.exit(1)
